import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/group_model.dart';
import 'package:flutter_qq/flutter_qq.dart';
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  List<GroupModel> groups;
  String selectedGroup="默认分组";
  final scaffoldState = GlobalKey<ScaffoldState>();
  String account = "";
  String password = "";
  bool showPass = false;
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  @override
  void initState() {
    super.initState();
  }

  String validateAccount(String value) {
    if (value == "") return "请输入手机号/邮箱";
    return null;
  }

  String validatePassword(String value) {
    if (value == "") return "请输入密码";
    return null;
  }

  login() async {
    var exist = await findDeviceByAccount(account);
    if (exist) {
      toast("账号已存在");
      return false;
    }
    Map loginInfo = await doLogin(account: account, password: password);
    if (loginInfo == null) {
      toast("登录出错");
    } else {
      var groupid=1;
      for(GroupModel group in groups){
        if(group.name==selectedGroup){
          groupid=group.id;
          break;
        }
      }
      int id = await addDevice(groupid, account, password, rand(), rand(), loginInfo['sessionid'], loginInfo['userid']);
      Navigator.pop(context, "$id");
    }
  }

  @override
  Widget build(BuildContext context){

    return new MaterialApp(
      theme: new ThemeData(
        accentColor: Colors.deepOrange,
        primaryColor: Colors.deepOrange,
      ),
      home: new Scaffold(
        key: scaffoldState,
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: Colors.deepOrange,
          middle: new Text(
            "添加账号",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          leading: new CupertinoButton(
            padding: EdgeInsets.all(0.0),
            child: new Icon(
              CupertinoIcons.back,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context, null);
            },
          ),
        ),
        body: new Container(
          padding: EdgeInsets.all(20.0),
          child: new Form(
            key: _formKey,
            child: new Column(
              children: <Widget>[
                new TextFormField(
                  decoration: new InputDecoration(
                    hintText: '请输入手机号/邮箱',
                    labelText: "账号",
                  ),
                  onSaved: (value) {
                    account = value;
                  },
                  validator: validateAccount,
                ),
                new TextFormField(
                  obscureText: this.showPass,
                  decoration: new InputDecoration(
                    hintText: '请输入玩客云密码',
                    labelText: '密码',
                    suffixIcon: new IconButton(
                        icon: new Icon(
                          this.showPass ? Icons.visibility : Icons.visibility_off,
                          color: Colors.black38,
                          size: 22.0,
                        ),
                        onPressed: () {
                          this.showPass = !this.showPass;
                          setState(() {});
                        }),
                  ),
                  onSaved: (value) {
                    password = value;
                  },
                  validator: validatePassword,
                ),
                new Container(
                  decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
                    color: Colors.deepOrange,
                  ),
                  margin: EdgeInsets.only(top: 20.0),
                  width: 160.0,
                  height: 40.0,
                  child: new FlatButton(
                      onPressed: () {
                        final FormState form = _formKey.currentState;
                        if (!form.validate()) {
                        } else {
                          form.save();
                          login();
                        }
                      },
                      child: new Text(
                        "确认添加",
                        style: new TextStyle(color: Colors.white),
                      )),
                ),
                new Container(
                  decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
                    color: Colors.deepOrange,
                  ),
                  margin: EdgeInsets.only(top: 20.0),
                  width: 160.0,
                  height: 40.0,
                  child: new FlatButton(
                      onPressed: () async{
                        FlutterQq.registerQQ("101475558");
                        var qqResult = await FlutterQq.login();
                        if (qqResult.code == 0) {
                          print(qqResult.message);
                          toast("登录成功");
                        } else if (qqResult.code == 1) {
                          print("登录失败"+qqResult.message);
                          toast("登录失败");
                        } else {
                          print("取消登录");
                          toast("取消登录");
                        }
                      },
                      child: new Text(
                        "QQ登录",
                        style: new TextStyle(color: Colors.white),
                      )),
                ),
                new Container(
                  decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
                    color: Colors.deepOrange,
                  ),
                  margin: EdgeInsets.only(top: 20.0),
                  width: 160.0,
                  height: 40.0,
                  child: new FlatButton(
                      onPressed: () async{
                        FlutterQq.registerQQ("101475558");
                        ShareQQContent shareContent = new ShareQQContent(
                          title: "测试title",
                          targetUrl: "https://www.baidu.com",
                          summary: "测试summary",
                          imageUrl: "http://inews.gtimg.com/newsapp_bt/0/876781763/1000",
                        );
                        try {
                          var qqResult = await FlutterQq.shareToQQ(shareContent);
                          var output;
                          if (qqResult.code == 0) {
                            output = "分享成功";
                          } else if (qqResult.code == 1) {
                            output = "分享失败" + qqResult.message;
                          } else {
                            output = "用户取消";
                          }
                          print(output);
                        } catch (error) {
                          print("flutter_plugin_qq_example:" + error.toString());
                        }
                      },
                      child: new Text(
                        "QQ分享",
                        style: new TextStyle(color: Colors.white),
                      )),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
